$(document).ready(function(){
	init();
});

function init(){
	window.ajaxCounter = 1;
    $('.button').button();
    $('#continue').click(function(){continueOnTrail()})
    $('.ui-widget-overlay').live("click", function() {
        //Close the dialog
        $("#changePaceForm").dialog("close");
        $('#changeRationsForm').dialog("close");
     });   
    $('#changePaceForm').dialog({
    		hide:'slide',
    		show:'slide',
    		modal:true,
			autoOpen:false,
			title:'Choose a new pace',
			buttons: { 
				"Change Pace": function(){submitPace()},
			}
    });
    $('#changeRationsForm').dialog({
		hide:'slide',
		show:'slide',
		modal:true,
		autoOpen:false,
		title:'Choose a new ration amount',
		buttons: { 
			"Change Rations": function(){submitRations()},
		}
});
    $('#changePaceButton').click(function(){$('#changePaceForm').dialog('open')});
    $('#changeRationsButton').click(function(){$('#changeRationsForm').dialog('open')});
}

function submitPace(){
	$.ajax({url:$('#changePaceForm').attr('url'),
		type: "GET",
		data: $('#changePaceForm>form').serialize(),
		dataType: 'html',
		success:function(info){
			$.notifyBar({
				html: 'Successfully changed pace to "' + info + '"',
				delay: 2000,
				animationSpeed: "normal",
				cls: "success"
			});
		},
		error:function(){
			$.notifyBar({
				html: 'Unable to change pace',
				delay: 2000,
				animationSpeed: "normal",
				cls: "error"
			});
		}
	});
	$('#changePaceForm').dialog('close');	
}

function continueOnTrail() {
	window.ajaxCounter += 1;
	d = new Date();
	$.ajax({url:$('#continue').attr('url') + '?r=' + (d.getTime()),
		type: "GET",
		dataType: 'json',
		success:function(info){
//			$.notifyBar({
//				html: 'Successfully changed rations to "' + info + '"',
//				delay: 2000,
//				animationSpeed: "normal",
//				cls: "success"
//			});
			if ('url' in info){
				window.location = info['url'];
			} else {
				$('#distTraveled').html(info['distTraveled']);
				$('#currFood').html(info['currFood']);
			}
		},
		error:function(){
			$.notifyBar({
				html: 'Unable to change rations',
				delay: 2000,
				animationSpeed: "normal",
				cls: "error"
			});
		}
	});
}

function submitRations(){
	$.ajax({url:$('#changeRationsForm').attr('url'),
		type: "GET",
		data: $('#changeRationsForm>form').serialize(),
		dataType: 'html',
		success:function(info){
			$.notifyBar({
				html: 'Successfully changed rations to "' + info + '"',
				delay: 2000,
				animationSpeed: "normal",
				cls: "success"
			});
		},
		error:function(){
			$.notifyBar({
				html: 'Unable to change rations',
				delay: 2000,
				animationSpeed: "normal",
				cls: "error"
			});
		}
	});
	$('#changeRationsForm').dialog('close');	
}